package org.mebusw.dao.proxy;

import java.util.List;

import org.mebusw.dao.IUserDAO;
import org.mebusw.dao.impl.IUserDAOImpl;
import org.mebusw.dbc.DataBaseConnection;
import org.mebusw.struts.vo.User;

/**
 * 
 * JSP should use DAOFactory to generate instance of IUserDAOProxy.
 * IUserDAOProxy create DB connection, then access DB.
 * @author j1shen
 * @see IUserDAOImpl
 *
 */
public class IUserDAOProxy implements IUserDAO {
	private DataBaseConnection dbc = null;
	private IUserDAO dao = null;
	private int count = 0;
	
	
	public IUserDAOProxy() {
		this.dbc = new DataBaseConnection();
		this.dao = new IUserDAOImpl(this.dbc.getConnection());
	}

	@Override
	public boolean doCreate(User user) throws Exception {
		boolean flag = false;
		try	{
			if (this.dao.findById(user.getUid()) == null)	{
				flag = this.dao.doCreate(user);
			}
		} catch (Exception e)	{
			throw e;
		} finally {
			this.dbc.close();
		}
		return flag;
	}

	@Override
	public boolean doDelete(int uid) throws Exception {
		boolean flag = false;
		try	{
			flag = this.dao.doDelete(uid);
		} catch (Exception e)	{
			throw e;
		} finally {
			this.dbc.close();
		}
		return flag;
	}

	@Override
	public boolean doUpdate(User user) throws Exception {
		boolean flag = false;
		try	{
			flag = this.dao.doUpdate(user);
		} catch (Exception e)	{
			throw e;
		} finally {
			this.dbc.close();
		}
		return flag;
	}

	@Override
	public List<User> findAll(int currentPage, int lineSize, String keyword)
			throws Exception {
		List<User> allUsers = null;
		try	{
			allUsers = this.dao.findAll(currentPage, lineSize, keyword);
			this.count = this.dao.getAllCount(keyword);
			
		} catch (Exception e)	{
			throw e;
		} finally {
			this.dbc.close();
		}
		return allUsers;
	}

	@Override
	public User findById(int uid) throws Exception {
		User user = null;
		try	{
			user = this.dao.findById(uid);
		} catch (Exception e)	{
			throw e;
		} finally {
			this.dbc.close();
		}
		return user;
	}

	@Override
	public int getAllCount(String keyword) throws Exception {
		return this.count;
	}

}
